package com.itheima.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.po.UserInfo;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.enums.UserStatus;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class IUserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void deductBalance(Long id, Integer money) {
        User user = getById(id);
        if (user == null || user.getStatus() == UserStatus.FROZEN) {
            throw new RuntimeException("用户不存在或已冻结");
        }
        if (user.getBalance() < money) {
            throw new RuntimeException("用户余额不足");
        }
//        baseMapper.deductBalance(id,money);
        int remainMoney = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance, remainMoney)
                .set(remainMoney == 0, User::getStatus, 0)
                .eq(User::getId, id)
                .eq(User::getBalance, user.getBalance())
                .update();
    }

    @Override
    public List<User> queryUsers(String name, Integer status, Integer maxBalance, Integer minBalance) {
        return lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .le(maxBalance != null, User::getBalance, maxBalance)
                .ge(minBalance != null, User::getBalance, minBalance)
                .list();
    }

    @Override
    public void addBatchUser() {
        List<User> users = new ArrayList<>();
        User user = new User();
        for (int i = 1; i <= 5; i++) {
            user.setUsername("username_" + i);
            user.setPassword("password" + i);
            user.setPhone(String.valueOf(17701265258L + i));
            user.setStatus(UserStatus.NORMAL);
            user.setBalance(i);
            user.setInfo(UserInfo.of(i, "英文老师", "female"));
            users.add(user);
            user = new User();
        }
        saveBatch(users);
    }

    @Override
    public UserVO getAddressById(Long id) {
        User user = lambdaQuery().eq(User::getId, id).one();
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        List<Address> list = Db.lambdaQuery(Address.class).eq(Address::getUserId, user.getId()).list();
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        userVO.setAddressVOS(BeanUtil.copyToList(list, AddressVO.class));
        return userVO;
    }

    @Override
    public List<UserVO> addressAndUserslistByIds(List<Long> ids) {
        List<User> users = listByIds(ids);
        List<UserVO> userVOS = BeanUtil.copyToList(users, UserVO.class);
        if (CollUtil.isEmpty(users)) {
            throw new RuntimeException("未查询到用户");
//            return userVOS;
        }
        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
        List<Address> addressList = Db.lambdaQuery(Address.class).in(Address::getUserId, userIds).list();
        if (CollUtil.isEmpty(addressList)) {
//            throw new RuntimeException("未查询到地址");
            return userVOS;
        }
        List<AddressVO> addressVOS = BeanUtil.copyToList(addressList, AddressVO.class);
        Map<Long, List<AddressVO>> addressmap = addressVOS.stream().collect(Collectors.groupingBy(AddressVO::getUserId));

        for (UserVO userVO : userVOS) {
            userVO.setAddressVOS(addressmap.get(userVO.getId()));
        }
        return userVOS;
    }

    @Override
    // ... existing code ...

    public IPage<UserVO> addressAndUsersPage(Page<UserVO> page, List<Long> ids) {
        return userMapper.addressAndUsersPage(page, ids);
    }

    @Override
    public PageDTO<UserVO> queryUsersPage(UserQuery userQuery) {
        String name = userQuery.getName();
        Integer status = userQuery.getStatus();
        Page<User> page=userQuery.toMpPageDefaultSortByUpdateTimeDesc();
        lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .page(page);

        return PageDTO.of(page, UserVO.class);
    }

// ... existing code ...

}
